package threading;

import java.util.concurrent.PriorityBlockingQueue;

class Task implements Comparable<Task>{
    public Runnable runnable;
    public long time;
    public Task(Runnable runnable ,long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;

    }


    @Override
    public int compareTo(Task o) {
        return (int)(this.time - o.time);
    }
}

class Timer {
    private PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>();

    Object locker = new Object();

    public void schedule(Runnable runnable, long delay) {
        Task task = new Task(runnable, delay);
        queue.put(task);
        synchronized (locker) {
            locker.notify();
        }
    }

    public Timer(){
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    synchronized (locker) {
                        Task task = queue.take();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= task.time) {
                            // 时间到了，执行任务
                            task.runnable.run();
                        } else {
                            // 时间没到
                            queue.put(task);
                            locker.wait(task.time - curTime);
                        }
                    }

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();
    }


}

public class ThreadDemo12 {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 4");
            }
        } , 4000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3");
            }
        } , 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2");
            }
        } , 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1");
            }
        } , 1000);
    }
}
